import { getCuesActiveDetails, selectAdopt } from '@/services/api/api-county';
import { CheckCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import { DrawerForm, ModalForm, ProFormDigit } from '@ant-design/pro-form';
import {
    Badge,
    Button,
    Card,
    Descriptions,
    Divider,
    Image,
    Modal,
    Space,
    Spin,
    Tag,
    Typography,
    Upload,
    UploadFile,
    message,
} from 'antd';
import moment from 'moment';
import React, { useState } from 'react';
import { useAccess } from 'umi';

interface DetailsActiveProps {
    table: string;//table 使用位置  
    tableAdoptAccountId?: string | undefined;
    id: string;
    name: string;
    onRefurbish: () => void;
    countyKey: string;
    item: CountyData.ActivePage;
    triggerMode: 'card' | 'title';
}

const DetailsActive: React.FC<DetailsActiveProps> = ({ table, tableAdoptAccountId, id, name, onRefurbish, countyKey,item,triggerMode }) => {
    const access = useAccess();

    const [details, setDetailsState] = useState<CountyData.ActiveDetails>();

    const [adoptDetails, setAdoptDetailsState] = useState<CountyData.AdoptForAccountVo>();


    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');

    const handleCancel = () => setPreviewOpen(false);

    /**
     * 获取 详情
     * @param key
     */
    const getActiveDetails = async () => {
        try {
            const response = await getCuesActiveDetails({ id, countyKey });
            if (response.code === 0) {
                setDetailsState(response.data);
            }
        } catch (error) { }
    };

    /**
   * 获取 该 用户 收录详情
   * @param key
   */
    const getAdopt = async () => {
        try {
            const response = await selectAdopt({ articleId: id, adoptAccountId: tableAdoptAccountId, type: 2 });
            if (response.code === 0) {
                setAdoptDetailsState(response.data);
            }
        } catch (error) { }
    };


    const getFileNameFromUrl = (url: string) => {
        const hashIndex = url.indexOf('?');
        url = hashIndex !== -1 ? url.substring(0, hashIndex) : url;
        return (url.split('/').pop() || '').replace(/[\?].*$/g, '');
    };

    const handlePreview = async (file: UploadFile) => {
        console.log('======', file.url);
        setPreviewTitle(file.name);
        setPreviewImage(file.url);
        setPreviewOpen(true);
    };

    return (
        <DrawerForm
            key="details_details_drawer_form"
            title={details?.articleName}
            drawerProps={{
                // maskClosable: false,
                destroyOnClose: true,
                width:'100%'
            }}
            trigger={
                triggerMode === 'card' ? (
                    <div
                        style={{
                            // paddingLeft: 10,
                            // paddingRight: 10,
                            paddingBottom: 10,
                        }}
                    >
                        <Card
                            bordered={false}
                            hoverable
                            style={{
                                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
                            }}
                        >
                            <Card.Meta

                                title={
                                   <div style={{ display: 'flex', justifyContent: 'space-between',width:'80vw' }}>
                                        <div
                                            style={{
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                minWidth: 65,
                                            }}
                                        >
                                            {item.articleOrganizationName}-{item.articleAccountName}
                                        </div>
                                        <div
                                            style={{
                                                float: 'left',
                                            }}
                                        >
                                            {item.isAdopt === 0 ? (
                                                <Tag color="#F9CF59">未录用</Tag>
                                            ) : (
                                                <Tag color="#1AA15F">已录用</Tag>
                                            )} 
                                        </div>
                                    </div>
                                }
                                description={
                                    <>
                                        <Typography.Paragraph ellipsis={true}>
                                            {
                                                <span
                                                    style={{
                                                        color: '#888A8C',
                                                        fontSize: 15,
                                                    }}
                                                >
                                                    {item.articleName}
                                                </span>
                                            }
                                        </Typography.Paragraph>
                                        <div>
                                            行业：
                                            <Tag key={item.value}>{item.articleIndustryName}</Tag>
                                        </div>
                                        <div
                                            style={{
                                                marginTop: 5,
                                            }}
                                        >
                                            标签：
                                            <Space size={[0, 8]} wrap>
                                                {item.articleLabels.slice(0, 1).map((item, index) => (
                                                    <Tag key={index}>
                                                        <div
                                                            style={{
                                                                whiteSpace: 'nowrap',
                                                                overflow: 'hidden',
                                                                textOverflow: 'ellipsis',
                                                                maxWidth: 100,
                                                            }}
                                                        >
                                                            {item}
                                                        </div>
                                                    </Tag>
                                                ))}
                                                {item.articleLabels.length > 1 ? '...' : ''}
                                            </Space>
                                        </div>
                                        <div
                                            style={{
                                                marginTop: 5,
                                                marginRight: 10,
                                            }}
                                        >
                                            <span
                                                style={{
                                                    float: 'left',
                                                }}
                                            >
                                                联络人:{item.articleAccountName}
                                            </span>
                                            <span
                                                style={{
                                                    float: 'right',
                                                }}
                                            >
                                                {moment(item.createdTime).fromNow()}
                                            </span>
                                        </div>
                                    </>
                                }
                            />
                        </Card>
                        <div
                            style={{
                                borderRadius: 12,
                                background: '#FFF',
                            }}
                        >
                        </div>
                    </div>
                ) : (
                    <a>{name}</a>
                )
            }
            onVisibleChange={(visible) => {
                if (visible) {
                    getActiveDetails();
                    if (table == "adopt") {
                        getAdopt()
                    }
                } else {
                    onRefurbish();
                }
            }}
            submitter={
                false
            }
            onFinish={async (values) => {

            }}
        >
            <Spin
                style={{
                    textAlign: 'center',
                }}
                spinning={details === undefined}
            >
                <Descriptions>
                    <>
                        <Descriptions.Item label="是否录用">
                            {details?.isAdopt === 0 ? '否' : '是'}
                        </Descriptions.Item>
                        <Descriptions.Item label="是否自己录用">
                            {details?.isSelfAdopt === 0 ? '否' : '是'}
                        </Descriptions.Item>
                        {/* {stringify(details?.score) === '{}' ? <></> :
                            <Descriptions.Item label="评分" >{stringify(details?.score) === '{}' ? '' : stringify(details?.score)}</Descriptions.Item>
                        } */}
                        {/* <Descriptions.Item label="录用次数">
                            <DetailsArticleAdopt
                                type={2}
                                articleId={details?.id}
                                countyKey={countyKey}
                                count={details?.countAdopt}
                                onRefurbish={function (): void {
                                    getActiveDetails();
                                    if (table == "adopt") {
                                        getAdopt()
                                    }
                                }}
                            />
                        </Descriptions.Item> */}
                    </>
                </Descriptions>

                <Divider />
                <Descriptions>
                    <Descriptions.Item label="报送单位">{details?.articleOrganizationName}</Descriptions.Item>
                    <Descriptions.Item label="报送人">{details?.articleAccountName}</Descriptions.Item>
                    <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item>
                    <Descriptions.Item label="报送时间">{details?.createdTime}</Descriptions.Item>
                </Descriptions>
                <Descriptions>
                    <Descriptions.Item label="行业">
                        <Tag>{details?.articleIndustryName}</Tag>
                    </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                    <Descriptions.Item label="标签">
                        {details?.articleLabels.map((item) => {
                            return <Tag key={item}>{item}</Tag>;
                        })}
                    </Descriptions.Item>
                </Descriptions>
                {details?.remarks && (
                    <Typography.Paragraph>
                        备注
                        {/* <blockquote>{details?.remarks}</blockquote> */}
                    </Typography.Paragraph>
                )}
                {table == "adopt" && adoptDetails && <>
                    <Divider />
                    <Typography.Title level={5}>
                        {adoptDetails.isInstruct === 0 && adoptDetails.cancelAccountId && <Tag color='red'>
                            取消
                        </Tag>}
                        <Tag color={adoptDetails?.isInstruct === 0 ? 'green' : 'orange'}>
                            {adoptDetails?.isInstruct === 0 ? '自主' : '指令'}
                        </Tag>
                        {adoptDetails?.organizationName} - {adoptDetails?.accountName}
                    </Typography.Title>
                    <Typography.Paragraph>
                        {adoptDetails?.isInstruct === 1 && (
                            <blockquote>指令人：{adoptDetails?.instructAccountName}</blockquote>
                        )}
                        {adoptDetails?.instructDescribes != null && adoptDetails?.instructDescribes != "" && (
                            <blockquote>指令描述：{adoptDetails?.instructDescribes}</blockquote>
                        )}
                        <blockquote>收录时间：{adoptDetails?.createdTime}</blockquote>
                        {adoptDetails.isInstruct === 0 && adoptDetails.cancelAccountId && (
                            <><blockquote>取消人：{adoptDetails.cancelAccountName}</blockquote>
                                <blockquote>取消时间：{adoptDetails.cancelTime}</blockquote>
                                <blockquote>取消描述：{adoptDetails.cancelDescribes}</blockquote></>
                        )}
                    </Typography.Paragraph>
                </>}
                <Divider />
                <Typography.Title level={3} style={{ textAlign: 'center' }}>
                    {details?.articleName}
                </Typography.Title>
                <br />
                <div
                    dangerouslySetInnerHTML={{
                        __html: `${details?.articleContent}`,
                    }}
                />
                {details?.articleAttachments && details?.articleAttachments.length > 0 && (
                    <>
                        <Divider />
                        <div
                            style={{
                                textAlign: 'right',
                            }}
                        >
                            <Button
                                type="primary"
                                key="import"
                                size="small"
                                icon={<DownloadOutlined />}
                                onClick={() => {
                                    details?.articleAttachments.forEach(function (item) {
                                        window.open(item.content, '_blank');
                                    });
                                }}
                            >
                                全部下载
                            </Button>
                        </div>

                        <Upload
                            listType="picture"
                            multiple
                            fileList={details?.articleAttachments.map((item) => {
                                return {
                                    uid: item.id,
                                    name: getFileNameFromUrl(item.content),
                                    url: item.content,
                                    status: 'done',
                                };
                            })}
                            showUploadList={{
                                downloadIcon: (
                                    <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                        <DownloadOutlined
                                            style={{
                                                marginRight: '10px',
                                            }}
                                        />
                                        点击下载
                                    </div>
                                ),
                                showRemoveIcon: false,
                                showDownloadIcon: true,
                            }}
                            onPreview={handlePreview}
                        />
                        <Modal visible={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
                            <Image width="100%" src={previewImage} />
                        </Modal>
                    </>
                )}
            </Spin>
        </DrawerForm>
    );
};

export default DetailsActive;
